import $ from '../utils';
var fs = require('fs');
var ALY = require('aliyun-sdk');
var formidable = require('formidable');
var path = require('path');




export default{
    uploadOne:(req,res)=>{

        // res.setTimeout(3000,function(){
        //     console.log("响应超时.");
        // });
        var form = new formidable.IncomingForm();

        var ossStream = require('aliyun-oss-upload-stream')(new ALY.OSS({
            accessKeyId: 'LTAIfomHskUA94Fg',
            secretAccessKey: 'wJWjoKwgoIW6s4gTm59Cfg3JhVoI0f',
            endpoint: 'http://oss-cn-shanghai.aliyuncs.com',
            apiVersion: '2013-10-15'
        }))


        let key = Math.floor(Math.random()*1000000000)+'message-ycb'+$.base.currentTime();
        var upload = ossStream.upload({
            Bucket: 'message-ycb',
            Key: key
        });



        //console.log(__dirname,'aaa')
        //console.log(path.dirname(__filename),'1111')

        form.parse(req, function(err, fields, files){
            //console.log(err,fields,files.file.path)
            var file = fs.createReadStream(files.file.path);

            file.on("open", function(fd) {
                console.log("开始读取文件：");
            });
            file.on("data", function(data) {
                console.log("读取到数据：");
                console.log(data);
            });
            file.on("end", function() {
                console.log("文件已全部读取完毕。");
            });
            file.on("close", function() {
                console.log("文件被关闭。");
            });
            file.on("error", function() {
                console.log("读取文件失败。");
                res.send(JSON.stringify({"status":'0',"msg":'图片上传失败',"dataset":[]}))
            });

            file.pipe(upload);
        })

        upload.minPartSize(1048576); // 1M，表示每块part大小至少大于1M

        upload.on('error', function (error) {
            console.log('error:', error);
            res.send(JSON.stringify({"status":'0',"msg":'图片上传失败',"dataset":[]}))
        });

        upload.on('part', function (part) {
            console.log('part:', part);
        });

        var startTime = new Date();

        upload.on('uploaded', function (details) {
            let buffer = [];
            let object = {'imageUrl':details.Location};
            buffer.push(object);


            res.send(JSON.stringify({"status":'1',"msg":'图片上传成功',"dataset":buffer}))
            var s = (new Date() - startTime) / 1000;
            console.log('details:', details);
            console.log('Completed upload in %d seconds', s);
        });


    }

}

